package com.shadow.demo.shiro.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.shadow.demo.data.shiro.entity.Role;
import com.shadow.demo.data.bo.Query;
import com.shadow.demo.data.shiro.entity.Permission;
import com.shadow.demo.data.shiro.entity.RolePermission;
import com.shadow.demo.data.shiro.mapper.PermissionMapper;
import com.shadow.demo.data.shiro.mapper.RolePermissionMapper;
import com.shadow.demo.shiro.dto.PermissionDTO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by shadow
 * on 2022-6-29.
 */
@Service
public class PermissionService extends BaseService<PermissionMapper, Permission> implements IService<Permission> {

    @Resource
    private PermissionMapper permissionMapper;
    @Resource
    private RolePermissionMapper rolePermissionMapper;

    /**
     * 通过角色获取权限列表
     *
     * @param roleId 角色id
     * @return {@link List} 权限列表
     * */
    public List<Permission> getPermissionListByRoleId(final String roleId) {
        LambdaQueryWrapper<RolePermission> rolePermissionWrapper = new LambdaQueryWrapper<RolePermission>()
                .eq(RolePermission::getRoleId, roleId);
        List<RolePermission> rolePermissionList = rolePermissionMapper.selectList(rolePermissionWrapper);
        if (CollectionUtils.isNotEmpty(rolePermissionList)) {
            LambdaQueryWrapper<Permission> roleWrapper = new LambdaQueryWrapper<Permission>()
                    .in(Permission::getId, rolePermissionList.stream().map(RolePermission::getPermissionId).collect(Collectors.toList()));
            return Collections.unmodifiableList(permissionMapper.selectList(roleWrapper));
        }
        return Collections.emptyList();
    }

    /**
     * 根据用户获取权限列表
     *
     * @param userAccount 用户账户
     * @return {@link List} 权限列表
     */
    public List<PermissionDTO> getPermissionListByUserAccount(final String userAccount) {
        // 获取数据
        List<Permission> permissionList = permissionMapper.getPermissionListByUserAccount(userAccount);
        // 数据转换, 得到所有父级节点
        Map<String, PermissionDTO> map = permissionList.stream()
                .filter(x -> !Objects.isNull(x) && StringUtils.equals(x.getParentId(), "0"))
                .map(x -> {
                    PermissionDTO permissionDTO = new PermissionDTO();
                    BeanUtils.copyProperties(x, permissionDTO);
                    permissionDTO.setText(x.getName());
                    return permissionDTO;
                })
                .collect(Collectors.toMap(PermissionDTO::getId, o -> o));
        if (MapUtils.isEmpty(map)) {
            return Collections.emptyList();
        }
        // 组装所有(非父级)的子节点
        for (Permission permission : permissionList) {
            // 如果节点有父节点，则将其添加到父节点的child列表中
            if (!StringUtils.equals(permission.getParentId(), "0")) {
                PermissionDTO parentNode = map.get(permission.getParentId());
                if (parentNode != null) {
                    PermissionDTO permissionDTO = new PermissionDTO();
                    BeanUtils.copyProperties(permission, permissionDTO);
                    permissionDTO.setText(permission.getName());
                    parentNode.addChildren(permissionDTO);
                }
            }
        }
        return map.values().stream()
                .peek(x -> {
                    if (!Objects.isNull(x.getChildren())) {
                        List<PermissionDTO> sortedChildren = x.getChildren()
                                .stream()
                                .sorted(Comparator.comparing(PermissionDTO::getOrderNum))
                                .collect(Collectors.toList());
                        x.setChildren(sortedChildren);
                    }
                })
                .sorted(Comparator.comparing(PermissionDTO::getOrderNum))
                .collect(Collectors.toList());
    }


    /**
     * 分页获取角色列表
     *
     * @param params 查询参数
     * @return {@link Role}
     * */
    public Page<Permission> getList(final Map<String, Object> params) {
        final String name = (String) params.get("name");
        final LambdaQueryWrapper<Permission> wrapper = new LambdaQueryWrapper<Permission>()
                .like(StringUtils.isNotBlank(name), Permission::getName, name)
                .orderByDesc(Permission::getCreateTime);
        return permissionMapper.selectPage(new Query<Permission>(params).getPage(), wrapper);
    }

    public List<Permission> getAllList() {
        return permissionMapper.selectList(null);
    }

    /**
     * 获取角色下所有的权限项
     * */
    public List<Permission> getAllByRoleId(final String roleId) {
        return permissionMapper.getAllByRoleId(roleId);
    }
}
